package com.mryao.gxkygl.common.aop;

import com.mryao.gxkygl.common.base.dao.SysLogRepository;
import com.mryao.gxkygl.common.base.entity.SysLog;
import com.mryao.gxkygl.common.exception.FieldErrorsException;
import com.mryao.gxkygl.common.result.Result;
import com.mryao.gxkygl.common.utils.CurrentUserUtils;
import com.mryao.gxkygl.common.utils.HttpContextUtils;
import com.mryao.gxkygl.common.utils.IPUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;

/**
 * @author: zmj
 * : 2020/10/20 9:55
 * @Description:
 * @Version: 1.0
 */
@Aspect
@Component
public class ControllerAspect {
    public static final Logger logger = LoggerFactory.getLogger(ControllerAspect.class);
    @Autowired
    private SysLogRepository sysLogRepository;

    /**
     * Controller层切点
     */
    @Pointcut("@annotation(com.mryao.gxkygl.common.aop.AutoErrorhandler)")
    public  void controllerAspect() {

    }

    @Around("controllerAspect()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        long beginTime = System.currentTimeMillis();
        Result result ;
        Object[] args = joinPoint.getArgs();
        for (Object arg : args) {
            if(arg instanceof BindingResult){
                BindingResult bindingResult = (BindingResult) arg;
                if(bindingResult.hasErrors()){
                    throw new FieldErrorsException("字段验证错误！",bindingResult.getFieldErrors());
//                    return Result.getError("字段验证错误!" + bindingResult.getFieldErrors().get(0).getDefaultMessage());
                }
            }
        }
        try {
            logger.info("方法：" + joinPoint.getSignature() + "， 参数：" + joinPoint.getArgs());
            result = (Result) joinPoint.proceed();
        }catch (Throwable throwable){
            result = handlerException(joinPoint, throwable);
        }finally {
            //执行时长(毫秒)
            long time = System.currentTimeMillis() - beginTime;
            //保存日志
            saveLog(joinPoint, time);
        }
        return result;
    }

    private void saveLog(ProceedingJoinPoint joinPoint, long time) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        SysLog sysLog = new SysLog();
        AutoErrorhandler logAnnotation = method.getAnnotation(AutoErrorhandler.class);
        if (logAnnotation != null) {
            //注解上的描述信息
            sysLog.setUrl(logAnnotation.value());
        }
        //请求的方法名
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = signature.getName();
        sysLog.setMethod(className + "." + methodName + "()");
        //请求的方法参数值
        Object[] args = joinPoint.getArgs();
        //请求的方法参数名称
        LocalVariableTableParameterNameDiscoverer u = new LocalVariableTableParameterNameDiscoverer();
        String[] paramNames = u.getParameterNames(method);
        if (args != null && paramNames != null) {
            String params = "";
            for (int i = 0; i < args.length; i++) {
                params += "  " + paramNames[i] + ": " + args[i];
            }
            sysLog.setParams(params);
        }
        //获取request
        HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
        //设置IP地址
        sysLog.setIp(IPUtils.getIpAddr(request));
        //从shiro中拿到用户名
        String username = CurrentUserUtils.getCurrentUser().getSecurityUserDto().getUserName();
        sysLog.setUsername(username);
        sysLog.setTime((int) time);
        Date date = new Date();
        sysLog.setCreateTime(date);
        sysLog.setCount(1);
        SysLog sysLogByOperation = sysLogRepository.findSysLogByOperation(logAnnotation.value(),IPUtils.getIpAddr(request),username);
        //        保存系统日志
        if(sysLogByOperation==null){
            sysLogRepository.save(sysLog);
        }else {
            sysLogByOperation.setCount(sysLogByOperation.getCount()+1);
            sysLogByOperation.setCreateTime(sysLog.getCreateTime());
            sysLogByOperation.setTime(sysLog.getTime());
            sysLogRepository.updateSysLogByOperation(sysLogByOperation.getCount()+1,sysLog.getCreateTime(),sysLog.getTime(),logAnnotation.value(),IPUtils.getIpAddr(request),username);
        }


    }

    private Result handlerException(ProceedingJoinPoint joinPoint, Throwable e) {
        Result result = null;
        if (e instanceof RuntimeException) {
            logger.error("RuntimeException{方法：" + joinPoint.getSignature() + "， 参数：" + joinPoint.getArgs() + ",异常：" + e.getMessage() + "}", e);
            result = Result.getError(e.getMessage());
        } else {
            logger.error("异常{方法：" + joinPoint.getSignature() + "， 参数：" + joinPoint.getArgs() + ",异常：" + e.getMessage() + "}", e);
            result = Result.getError(e.getMessage());
        }
        return result;
    }
}
